import { useSyncExternalStore } from 'react';

interface StoreItem {
  value: any,
  dispatch: Set<any>
}

interface Store {
  [key: string]: StoreItem
}

let store: Store = {
  counter01: {
    value: 0,
    dispatch: new Set()
  },
  counter02: {
    value: 0,
    dispatch: new Set()
  },
  counter03: {
    value: 0,
    dispatch: new Set()
  },
  counter04: {
    value: 0,
    dispatch: new Set()
  },
}

function getSnapshot() {
  return store
}

function _setValue(key: string, value: any) {
  store[key].value = value
  console.log(store[key].dispatch)
  store[key].dispatch.forEach(cb => {
    cb()
  })
  return {...store}
}

export function useSubscribe(key: string, value: any = 0) {
  const store = useSyncExternalStore((callback: () => any) => {
    store[key].dispatch.add(callback)
    return () => {
      store[key].dispatch.delete(callback)
    }
  }, getSnapshot)

  return [store[key].value, (value: any) => _setValue(key, value)]  
}

export function useDispatch(key: string) {
  return (value: any) => _setValue(key, value)
}